# py实现sockete服务器，用于通讯协议测试
import numpy as np
import cv2
import sys
import json
import base64
import socket
 
def socket_service_image():
    try:
        s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
        s.bind(('127.0.0.1', 8899))
        s.listen(10)
    except socket.error as msg:
        print(msg)
        sys.exit(1)
    print("Wait for Connection.....................")
    while True:
        sock, addr = s.accept()
        deal_image(sock, addr)
 
def deal_image(sock, addr):
    print("Accept connection from {0}".format(addr))
    while True:
        buf = sock.recv(204800)
        json_dict = json.loads(buf)
        b64decoded = base64.b64decode(json_dict["imageb64"])                # 'bytes'
        image_ndarray = np.asarray(bytearray(b64decoded), dtype="uint8")    # 'numpy.ndarray'
        image = cv2.imdecode(image_ndarray, cv2.IMREAD_COLOR)
        if json_dict["detect_results"] != []:
            print("Detect results:", json_dict["detect_results"])
        if json_dict["corner_results"] != []:
            print("Corner results:", json_dict["corner_results"])
        cv2.imshow('image by server', image)
        cv2.waitKey(1)
 
if __name__ == '__main__':
    socket_service_image()